package com.sdy.healthcode.h5.task;

import com.sdy.common.utils.DateUtil;
import com.sdy.healthcode.biz.model.ApplyPost;
import com.sdy.healthcode.biz.model.HealthCode;
import com.sdy.healthcode.biz.service.ApplyPostService;
import com.sdy.healthcode.biz.service.HealthCodeService;
import com.sdy.mvc.annotation.TaskSync;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class CodeExpireTask {
    @Autowired
    private ApplyPostService applyPostService;
    @Autowired
    private HealthCodeService healthCodeService;

    @Scheduled(cron = "15 0 0 * * ?")
//    @Scheduled(cron = "0/10 * * * * ?")
    @TaskSync
    public void expire() {
        log.info("开始健康码清理工作...");
        Date dateBegin = DateUtil.getDateBegin(new Date());
        List<ApplyPost> applyPostList = applyPostService.lambdaQuery()
                .in(ApplyPost::getType, 2)
                .lt(ApplyPost::getAppointmentTime, dateBegin)
                .eq(ApplyPost::getState, 1)
                .list();
        if (!applyPostList.isEmpty()) {
            healthCodeService.lambdaUpdate()
                    .in(HealthCode::getType, 2)
                    .eq(HealthCode::getState, 1)
                    .in(HealthCode::getUserId, applyPostList.stream().map(ApplyPost::getUserId).collect(Collectors.toSet()))
                    .in(HealthCode::getApplyPostId, applyPostList.stream().map(ApplyPost::getId).collect(Collectors.toSet()))
                    .set(HealthCode::getState, 2)
                    .update();
            applyPostService.lambdaUpdate()
                    .in(ApplyPost::getId, applyPostList.stream().map(ApplyPost::getId).collect(Collectors.toSet()))
                    .set(ApplyPost::getState, 2)
                    .update();
        }
        log.info("健康码清理工作结束。");
    }
}
